package LinkedLists;
/**
 * 面试题 02.07. 链表相交
 */
import LinkedLists.init.ListNode;

public class mianshiti0207 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode cura = headA;
        ListNode curb = headB;
        int lena = 0, lenb = 0;
        while (cura != null) {
            lena++;
            cura = cura.next;
        }
        while (curb != null) {
            lenb++;
            curb = curb.next;
        }
        cura = headA;
        curb = headB;
        if (lenb > lena) {
            int templen = lena;
            lena = lenb;
            lenb = templen;
            ListNode temp = cura;
            cura = curb;
            curb = temp;
        }
        int gap = lena - lenb;
        while (gap-- > 0) {
            cura = cura.next;
        }
        while (cura != null) {
            if (cura == curb) {
                return cura;
            }
            cura = cura.next;
            curb = curb.next;
        }
        return null;
    }
}
